package com.yunduo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunduo.common.JwtUtils;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.YunDuoConst.OrderQueueParam;
import com.yunduo.common.YunDuoConst.OrderState;
import com.yunduo.common.YunDuoConst.ShopCarParam;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.*;
import com.yunduo.entity.front.ShopCar;
import com.yunduo.entity.front.ShopCarItem;
import com.yunduo.entity.vo.OrderQuery;
import com.yunduo.handler.exceptionhandler.OperationException;
import com.yunduo.module.OrderCouponPayContext;
import com.yunduo.service.*;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author ChengXin
 * @since 2023-08-25
 */
@RequiresRoles("user")
@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private PayService payService;
    //订单服务
    @Resource
    private OrderService orderService;
    //消息队列
    @Resource
    private RabbitTemplate rabbitTemplate;
    //redis
    @Resource
    private RedisTemplate redisTemplate;
    //商品服务
    @Resource
    private GoodService goodService;
    //计算优惠价格
    @Resource
    private OrderCouponPayContext orderCouponPay;
    //用户服务
    @Resource
    private UserService userService;
    //地址服务
    @Resource
    private AddressService addressService;


    //订单生成
    @PostMapping("/create")
    public CommonReturn createOrder(){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        ShopCar car = (ShopCar)redisTemplate.opsForHash().get(ShopCarParam.SHOPCAR_REDIS,user.getId());
        if(car.getGoods() == null || car.getGoods().size() == 0){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        BigDecimal total = new BigDecimal(0);
        StringBuffer shopInfo = new StringBuffer();
        Iterator<ShopCarItem> iterator = car.getGoods().iterator();
        //计算总价
        while (iterator.hasNext()){
            ShopCarItem item = iterator.next();
            Good good = goodService.getById(item.getGoodId());
            Double price = good.getPrice() * item.getCount();
            BigDecimal data = new BigDecimal(price.toString());
            total = total.add(data);
            shopInfo.append(good.getId()+"*"+item.getCount()+",");
        }
        Order order = new Order();
        order.setUserId(user.getId());
        order.setCouponId("优惠券id");
        order.setFreight(new BigDecimal("0"));
        order.setTotal(total);
        order.setPay(orderCouponPay.calculation(total,"优惠券id"));
        order.setShop(shopInfo.toString());
        order.setState(OrderState.DELAY_PAY);
        //添加默认地址
        Address deAddress = addressService.getOne(new LambdaQueryWrapper<Address>().eq(Address::getUserId, user.getId()).eq(Address::getPreset, true));
        order.setAddress(deAddress.getId());
        orderService.save(order);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("order",order.getId());
    }

    //支付方式
    @PostMapping("/payType")
    public CommonReturn payType(String type){
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //订单修改
    @PostMapping("/update")
    public CommonReturn updateOrder(@RequestBody Order order){
        if(StringUtils.isEmpty(order)){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        orderService.updateById(order);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //订单查询
    @GetMapping("/get/{id}")
    public CommonReturn getOrderById(@PathVariable("id") String id){
        Order order = orderService.getById(id);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("order",order);
    }

    //订单分页查询
    @PostMapping("/pages")
    public CommonReturn pageOrder(@RequestBody OrderQuery orderQuery){
        LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(!StringUtils.isEmpty(orderQuery.getUserId()), Order::getUserId,orderQuery.getUserId());
        orderWrapper.eq(checkState(orderQuery.getState()),Order::getState,orderQuery.getState());
        if(!StringUtils.isEmpty(orderQuery.getCreateBegin())){
            LocalDateTime begin = YunDuoUtils.splitDateString(orderQuery.getCreateBegin());
            orderWrapper.ge(Order::getGmtCreate,begin);
        }
        if(!StringUtils.isEmpty(orderQuery.getCreateEnd())){
            LocalDateTime end = YunDuoUtils.splitDateString(orderQuery.getCreateEnd());
            orderWrapper.le(Order::getGmtCreate,end);
        }
        Page<Order> orderPage = new Page<>(orderQuery.getCurrentPage(),orderQuery.getPageItems());
        IPage<Order> page = orderService.page(orderPage, orderWrapper);
        List<Order> orderData = page.getRecords();
        Iterator<Order> iterator = orderData.iterator();
        while (iterator.hasNext()){
            Order item = iterator.next();
            User user = userService.getById(item.getUserId());
            item.setUserId(user.getName());
        }
        HashMap<String,Object> data = new HashMap<>();
        data.put("list",orderData);
        data.put("listSize",orderData.size());
        data.put("total",page.getTotal());
        data.put("current",page.getCurrent());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS,data);
    }

    //订单状态修改
    @PostMapping("/updateState")
    public CommonReturn orderStateUpdate(@RequestBody Order param){
        boolean stateIsExist = checkState(param.getState());
        if(!stateIsExist || StringUtils.isEmpty(param.getId())){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        String id = param.getId();
        String state = param.getState();
        Order order = new Order();
        order.setId(id);
        order.setState(state);
        boolean isUpdate = orderService.updateById(order);
        if(!isUpdate){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("order",order);
    }
    //检查状态是否存在
    private boolean checkState(String state){
        if (StringUtils.isEmpty(state)) {
            return false;
        }
        switch (state){
            case "0":
                break;
            case "1":
                break;
            case "2":
                break;
            case "3":
                break;
            case "4":
                break;
            case "5":
                break;
            default:
                throw new OperationException(ResultCode.ERROR);
        }
        return true;
    }
}
